package baidu

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
	"time"
)

const BDAPPID = "33349312"
const BDAPPKEY = "78wYQTzFFHRX0htWOKvx3Bt4"
const BDAPPSEC = "bssUxjnfkr3ehE3Fh8mdK9v4Ip6CcMlC"

var bdAccessToken string

type Baidu struct {
	AccessToken string
	ExpireAt    time.Time
}

var baidu *Baidu

type GetAccessTokenStruct struct {
	ExpiresIn   int    `json:"expires_in"`
	AccessToken string `json:"access_token"`
}

func GetBaidu() *Baidu {
	if baidu == nil {
		baidu = new(Baidu)
		getAccessToken()
	}
	return baidu
}

func GetAccessToken() string {
	return GetBaidu().AccessToken
}

func getAccessToken() {

	url := fmt.Sprintf("https://aip.baidubce.com/oauth/2.0/token?client_id=%s&client_secret=%s&grant_type=client_credentials", BDAPPKEY, BDAPPSEC)
	payload := strings.NewReader(``)
	client := &http.Client{}
	req, err := http.NewRequest("POST", url, payload)

	if err != nil {
		fmt.Println(err)
		return
	}
	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Accept", "application/json")

	res, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer res.Body.Close()

	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		fmt.Println(err)
		return
	}
	got := new(GetAccessTokenStruct)
	e := json.Unmarshal(body, &got)
	if e != nil {
		println(e)
	}
	baidu.AccessToken = got.AccessToken
}
